/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import os, { CpuInfo } from 'os';
import { parentPort } from 'worker_threads';

/**
 * 计算CPU平均使用率
 *
 * @param lastIdleTicks 上一次在idle模式下的毫秒数
 * @param lastTotalTicks 上一次的总毫秒数
 */
function cpuAvgUsage(lastIdleTicks: number, lastTotalTicks: number) {
  let idleTicks = 0;
  let totalTicks = 0;

  const cpus: CpuInfo[] = os.cpus();

  for (const cpu of cpus) {
    totalTicks += cpu.times.idle;
    totalTicks += cpu.times.irq;
    totalTicks += cpu.times.sys;
    totalTicks += cpu.times.nice;
    totalTicks += cpu.times.user;
    idleTicks += cpu.times.idle;
  }

  const idle: number = idleTicks - lastIdleTicks;
  const total: number = totalTicks - lastTotalTicks;
  const cpuUsage: number = 1 - idle / total;

  return {
    idleTicks,
    totalTicks,
    cpuUsage,
  };
}

let res = { idleTicks: 0, totalTicks: 0, cpuUsage: 0 };

setInterval(() => {
  res = cpuAvgUsage(res.idleTicks, res.totalTicks);
  parentPort!.postMessage(res.cpuUsage);
}, 100);
